import { useState, useCallback, useEffect } from 'react';
import { message } from 'antd';
import { usePagination, PaginationConfig } from './usePagination';

export interface UseTableDataConfig<T> extends PaginationConfig {
  fetchData: (params: any) => Promise<{ data?: { list: T[]; total: number } } | { list: T[]; total: number }>;
  onError?: (error: any) => void;
  defaultSearchParams?: any;
}

export interface UseTableDataResult<T> {
  data: T[];
  loading: boolean;
  searchParams: any;
  pagination: ReturnType<typeof usePagination>['pagination'];
  paginationConfig: ReturnType<typeof usePagination>['paginationConfig'];
  refresh: () => Promise<void>;
  search: (params: any) => void;
  reset: () => void;
  setSearchParams: (params: any) => void;
}

export const useTableData = <T = any>(config: UseTableDataConfig<T>): UseTableDataResult<T> => {
  const { fetchData, onError, defaultSearchParams = {}, ...paginationConfig } = config;
  
  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParamsState] = useState(defaultSearchParams);

  const { pagination, paginationConfig: tablePaginationConfig, setPagination, resetPagination } = usePagination(paginationConfig);

  const loadData = useCallback(async (params: any = {}) => {
    setLoading(true);
    try {
      const finalParams = {
        ...searchParams,
        ...params,
        page: pagination.current,
        pageSize: pagination.pageSize,
      };
      
      const response = await fetchData(finalParams);
      
      // 处理不同的响应数据结构
      const responseData = response.data || response;
      const list = responseData.list || [];
      const total = responseData.total || 0;
      
      setData(list);
      setPagination({ total });
    } catch (error) {
      if (onError) {
        onError(error);
      } else {
        message.error('获取数据失败');
      }
    } finally {
      setLoading(false);
    }
  }, [searchParams, pagination.current, pagination.pageSize, fetchData, setPagination, onError]);

  const refresh = useCallback(() => {
    return loadData();
  }, [loadData]);

  const search = useCallback((params: any) => {
    // 处理日期范围参数
    const processedParams = { ...params };
    if (params.createTimeRange && params.createTimeRange.length === 2) {
      processedParams.createTimeStart = params.createTimeRange[0].format('YYYY-MM-DD');
      processedParams.createTimeEnd = params.createTimeRange[1].format('YYYY-MM-DD');
      delete processedParams.createTimeRange;
    }
    
    setSearchParamsState(processedParams);
    setPagination({ current: 1 }); // 重置到第一页
  }, [setPagination]);

  const reset = useCallback(() => {
    setSearchParamsState(defaultSearchParams);
    resetPagination();
  }, [defaultSearchParams, resetPagination]);

  const setSearchParams = useCallback((params: any) => {
    setSearchParamsState(params);
  }, []);

  // 当分页或搜索参数变化时重新加载数据
  useEffect(() => {
    loadData();
  }, [pagination.current, pagination.pageSize, searchParams]);

  return {
    data,
    loading,
    searchParams,
    pagination,
    paginationConfig: tablePaginationConfig,
    refresh,
    search,
    reset,
    setSearchParams,
  };
};